package com.ultimate.management.config;

import com.ultimate.management.filter.JwtAuthenticationTokenFilter;
import com.ultimate.management.handler.AccessDeniedHandlerImpl;
import com.ultimate.management.handler.AuthenticationEntryPointImpl;
import com.ultimate.management.handler.LoginFailureHandler;
import com.ultimate.management.handler.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * @Author LH
 * @Date 2024/1/23 14:09
 * @PackageName com.ultimate.management.config
 * @Description: security配置类
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
//实现Security提供的WebSecurityConfigurerAdapter类，就可以改变密码校验的规则了
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    //把BCryptPasswordEncoder对象注入Spring容器中，SpringSecurity就会使用该PasswordEncoder来进行密码校验
    //注意也可以注入PasswordEncoder，效果是一样的，因为PasswordEncoder是BCry..的父类
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;


    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;


    @Autowired
    private LoginSuccessHandler loginSuccessHandler;
    @Autowired
    private LoginFailureHandler loginFailureHandler;


    //swagger资源
    private static final String[] AUTH_WHITELIST = {
            "/swagger-resources/**",
            "/swagger-ui.html",
            "/v2/api-docs",
            "/webjars/**",
            "/swagger-ui/**"
    };


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //由于是前后端分离项目，所以要关闭csrf
                .csrf().disable()
                //由于是前后端分离项目，所以session是失效的，我们就不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //指定让spring security放行登录接口的规则
                .authorizeRequests()
                // 对于登录接口 anonymous表示允许匿名访问
                .antMatchers("/user/login").anonymous()
//                .antMatchers("/user/info").authenticated()
                .antMatchers("/sys/tt").anonymous()
                .antMatchers("/test/**").anonymous()
                .antMatchers(AUTH_WHITELIST).anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
        //把token校验过滤器添加到过滤器链中
        //第一个参数是上面注入的我们在filter目录写好的类，第二个参数表示你想添加到哪个过滤器之前
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //springsecurity登录成功后的返回值

        http.formLogin(formLogin -> formLogin
                .loginProcessingUrl("/user/login").permitAll()//允许任何人访问
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
        );

        //---------------------------异常处理的相关配置-------------------------------

        http.exceptionHandling()
                //配置认证失败的处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                //配置授权失败的处理器
                .accessDeniedHandler(accessDeniedHandler);

        // 记住我--->key是一个加密密钥
            http.rememberMe(e -> e.rememberMeParameter("rememberMe").rememberMeCookieName("rememberMe").key("myKey"));
        //退出时删除记住我
//            http.logout(e -> e.invalidateHttpSession(true).deleteCookies("rememberMe"));
        //---------------------------👇 设置security运行跨域访问 👇------------------

        http.cors();

        //---------------------------👆 设置security运行跨域访问 👆------------------

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
